package com.chml.controller;

import com.chml.dto.LoginMessageDTO;
import com.chml.exception.FailCallException;
import com.chml.params.ChangePasswordParam;
import com.chml.params.CreateAccountParam;
import com.chml.params.LoginParam;
import com.chml.pojo.User;
import com.chml.service.UserService;
import com.chml.util.MD5Util;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 与用户相关的操作，包括注册用户，登录验证以及修改密码
 */
@Controller
@RequestMapping("/api")
public class UserController {
    @Resource
    private UserService userService;
    private static Logger logger = LogManager.getRootLogger();
    private String error_message = "后台错误，请联系系统管理员";

    /**
     * 验证登录是否合法
     *
     * @param param
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> Login(@RequestBody LoginParam param, HttpServletResponse response) {
        //response.setHeader("Access-Control-Allow-Origin","*");
        logger.log(Level.DEBUG, "Login function");
        String account = param.getAccount();
        String password = MD5Util.GetMD5Code(param.getPassword());
        logger.log(Level.DEBUG, account + " " + password);
        Map<String, Object> result = new HashMap<>();

        try {
            User user = userService.Login(account, password);
            if (user != null) {
                if (user.getPassword().equals(password)) {
                    LoginMessageDTO user_message = new LoginMessageDTO();
                    user_message.setAccess_token(user.getAccessToken());
                    Date lastDate = user.getLastAuthorizeTime();
                    Date currentDate = new Date();
                    int expire_time = (int) (7200 - ((currentDate.getTime() - lastDate.getTime()) / 1000));
                    user_message.setExpires_in(expire_time);
                    user_message.setUid(user.getUid());
                    user_message.setName(user.getUsername());
                    result.put("success", true);
                    result.put("msg", "登录成功");
                    result.put("User", user_message);
                } else {
                    result.put("success", false);
                    result.put("msg", "密码错误");
                }
            } else {
                result.put("success", false);
                result.put("msg", "用户名不存在");
            }
        } catch (Exception e) {
            logger.error("SomeThing is wrong:\n", e);
            result.put("success", false);
            result.put("mag", error_message);
            logger.log(Level.ERROR, e.getMessage());
        }
        return result;
    }

    /**
     * 修改密码
     *
     * @param uid
     * @param param
     * @param response
     * @return
     */
    @RequestMapping(value = "/user/{uid}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> ChangePassword(@PathVariable int uid, @RequestBody ChangePasswordParam param, HttpServletResponse response) {
        logger.log(Level.DEBUG, "ChangePassword function");
        String old_password = MD5Util.GetMD5Code(param.getOld_password());
        String new_password = MD5Util.GetMD5Code(param.getNew_password());
        String access_token = param.getAccess_token();
        logger.log(Level.DEBUG, old_password + " " + new_password + " " + access_token);
        Map<String, Object> result = new HashMap<>();
        try {
            int opCode = userService.ChangePassword(uid, old_password, new_password, access_token);
            if (opCode == 1) {
                result.put("success", true);
                result.put("msg", "修改成功, 请使用新密码重新登录");
            } else if (opCode == 0) {
                result.put("success", false);
                result.put("msg", "原密码错误");
            } else if (opCode == -1) {
                result.put("success", false);
                result.put("msg", "用户不存在");
            } else if (opCode == 2) {
                result.put("success", false);
                result.put("msg", "登录状态已失效,请重新登录");
            }
        } catch (Exception e) {
            logger.error("SomeThing is wrong:\n", e);
            result.put("success", false);
            result.put("msg", error_message);
            logger.log(Level.ERROR, e.getMessage());
        }
        return result;
    }

    /**
     * 注册新用户
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createAccount(@RequestBody CreateAccountParam param) {
        logger.log(Level.DEBUG, "createAccount function");
        Map<String, Object> result = new HashMap<>();
        logger.log(Level.DEBUG, param.getUid() + " " + param.getAccess_token());
        try {
            if (userService.isValidRequest(param.getUid(), param.getAccess_token())) {
                int stat = userService.createUser(param.getAccount(), MD5Util.GetMD5Code(param.getPassword()), param.getNickname());
                if (stat == -1) {
                    result.put("success", false);
                    result.put("msg", "账号已存在");
                } else {
                    result.put("success", true);
                    result.put("msg", "创建用户成功");
                }
            } else {
                result.put("success", false);
                result.put("msg", "登录状态已失效,请重新登录");
            }
        } catch (Exception e) {
            logger.error("SomeThing is wrong:\n", e);
            result.put("success", false);
            result.put("msg", error_message);
            logger.log(Level.ERROR, e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/user/base",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> currentUserBaseInfo(@RequestHeader(value = "access_token",required = false) String accessToken) {
        logger.debug("currentUserBaseInfo method call");
        User user = userService.getUserByToken(accessToken);
        Map<String, Object> result = new HashMap<>();
        try {
            if (!userService.isValidRequest(accessToken))
                throw new FailCallException("无效的token", 101);
            result.put("success", true);
            result.put("msg", "查询成功");
            result.put("code", 0);
            Map<String, Object> data = new HashMap<>();
            data.put("name", user.getUsername());
            result.put("data", data);
        } catch (FailCallException e) {
            logger.error(e);
            result.put("success", false);
            result.put("msg", e.getMessage());
            result.put("code", 101);
        } catch (Exception e) {
            logger.error(e);
            result.put("success", false);
            result.put("msg", error_message);
            result.put("code", 400);
        }
        return result;
    }
}